package com.alex.keywordtool;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

public class Adwords {

	public static void main(String[] args) throws Exception {
		Set<AdwordsKeyword> keywords = new HashSet<AdwordsKeyword>();
		
		String file = "/home/alex/Desktop/himc-keywords/all.csv";
		String out = "/home/alex/Desktop/himc-keywords/weighted.csv";
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
		String line = null;
		while ((line = reader.readLine()) != null) {
			if (line.startsWith("Keyword,")) {
				continue;
			}
			String[] parts = line.split(",");
			int searches;
			try {
				searches = Integer.parseInt(parts[2]);
			} catch (NumberFormatException e) {
				searches = 1;
			}
			keywords.add(new AdwordsKeyword(parts[0], searches));
		}
		
		BufferedWriter writer = new BufferedWriter(new FileWriter(out));
		
		for (AdwordsKeyword keyword : keywords) {
			int weight = (int) Math.ceil(logOfBase(20, keyword.searches));
			for (int i = 0; i < weight; i++) {
				writer.write(keyword.keyword + "\n");
			}
		}
		
		writer.close();
	}
	
	public static double logOfBase(int base, int num) {  
	    return Math.log(num) / Math.log(base); 
	}
}

class AdwordsKeyword {

	String keyword;

	int searches;

	public AdwordsKeyword(String keyword, int searches) {
		this.keyword = keyword;
		this.searches = searches;
	}
	
	@Override
	public int hashCode() {
		return keyword.hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		AdwordsKeyword another = (AdwordsKeyword) obj;
		return keyword.equals(another.keyword);
	}
}
